const db = require('../..//db');

//展示全部订单，输入用户id，按创建时间降序
exports.getOrderbyID = (req, res) => {
    //const user_id = req.params.user_id;
    const order_id = req.params.order_id;
    const q = "SELECT * FROM module2_order where order_id = ? ;";
    db.query(q, order_id,(err, results) => {
        if (err) return(err.message)
        res.send({
            status: 0,
            message: '数据返回成功！',
            data: results,
        })
    });
};

exports.getAllOrder = (req, res) => {
     const user_id = req.params.user_id;

     const q = "SELECT * FROM module2_order order by creation_date desc;";

     const values = [user_id, user_id];

     db.query(q,  (err, results) => {
         if (err) return res.cc(err);
         res.send({
             status: 0,
             message: '获取订单列表成功！',
             data: results,
         });
     });
};

//输入订单的全部信息
exports.addNewOrder = (req, res) => {
    const q = "INSERT INTO module2_order (buyer_id, seller_id, commodity_id,  amount, goods_name) VALUES (?, ?, ?, ?, ?);";

    const values = [req.params.buyer_id, req.params.seller_id, req.params.commodity_id, req.params.amount, req.params.goods_name];
    // const values = {
    //     buyer_id: req.params.buyer_id,
    //     seller_id: req.params.seller_id,
    //     goods_id: req.params.goods_id,
    //     amount: req.params.amount,
    //     goods_name: req.params.goods_name,
    // };
    db.query(q, values, (err, results) => {
        if (err) {
            console.error("插入失败" + err.message);
        }
        else {
            res.send({
                status: 0,
                message: '插入成功！',
                data: results,
            })
        }
    });
};

exports.updateOrderState = (orderId, newState, callback) => {
  const q = "UPDATE module2_order SET order_state = ?  WHERE order_id = ? ;";
  const values = [newState, orderId];
  db.query(q, values, (err, results) => {
    if (err) {
      callback(err);
    } else if (results.affectedRows !== 1) {
      callback(new Error("更新失败，请稍后再试！"));
    } else {
      callback(null, "更新成功！", 0);
    }
  });
};

exports.orderSearch = (req, res) => {

    let q = "SELECT * FROM module2_order WHERE (buyer_id = ? or seller_id = ?)";
    date = req.params.date;
    console.log('date:');
    console.log(date);

    if (req.params.date != '*' && req.params.date != '0' && req.params.date != '1' && req.params.date != '2') {
        q += " AND creation_date >= DATE_SUB(NOW(),Interval ? month)";
    }

    if (req.params.date == '1' || req.params.date == '2') {
        q += " AND creation_date >= DATE_SUB(NOW(),Interval ? day)";
    }

    if (req.params.searchkey != '*') {
        q += " AND (goods_name LIKE ? OR order_id LIKE ?)"
    }

    const arr = req.params.order_state.split(',').map(Number);
    console.log(arr);
    const user_id = req.params.user_id;
    const values = [];
    values.push(user_id);
    values.push(user_id);

    const datemap = new Map([['1', 1], ['2', 7], ['3', 1], ['4', 3], ['5', 12], ['6', 36]]);

    if (req.params.date != '0') {
        const date = datemap.get(req.params.date);
        values.push(date);
    }
    const searchkey = req.params.searchkey;
    console.log('searchkey:');
    console.log(searchkey);
    if (searchkey != '*') {
        values.push(`%${searchkey}%`);
        values.push(`%${searchkey}%`);
    }
    let flagexist = false;
    let flagstate = false;
    let flagrefund = false;
    let flagcomplaint = false;
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] == "0") {
            flagexist = true;
        }
        if (arr[i] == 1 || arr[i] == 2 || arr[i] == 3 || arr[i] == 4) {
            flagstate = true;
        }
        if (arr[i] == 5) {
            flagrefund = true;
        }
        if (arr[i] == 6) {
            flagcomplaint = true;
        }
    }
    if (flagexist == false) {
        if (flagstate) {
            q += " AND order_state in (";
            for (i = 0; i < arr.length; i++) {
                if (arr[i] == 1 || arr[i] == 2 || arr[i] == 3 || arr[i] == 4) {
                    q += "?,";
                    values.push(arr[i] - 1);
                }
            }
            if (q.endsWith(",")) {
                q = q.slice(0, -1);
            }
            q += ")";
        }
    }
    if (flagrefund) {
        q += " AND refund = 1";
    }
    if (flagcomplaint) {
        q += " AND complaint = 1";
    }
    q+=" order by creation_date desc";
    q += ";"
    console.log(q);
    console.log(values);
    db.query(q, values, (err, results) => {
        if (err) return res.cc(err);
        //else if(results.length===0) return res.cc("查询成功，但无符合条件的订单！");
        res.send({
            "status": 0,
            "message": "查询成功！",
            "data": results,
        });
    });
};


exports.updateIsRefund = (orderId, newState, callback) => {
    const q = "UPDATE module2_order SET refund = ?  WHERE order_id = ?  ;";
    const values = [newState, orderId];
    db.query(q, values, (err, results) => {
        if (err) {
            callback(err);
        } else if (results.affectedRows !== 1) {
            callback(new Error("更新失败，请稍后再试！"));
        } else {
            callback(null, "更新成功！", 0);
        }
    });
};
  
exports.updateIsComplaint = (orderId, newState, callback) => {
    const q = "UPDATE module2_order SET complaint = ?  WHERE order_id = ?  ;";
    const values = [newState, orderId];
    db.query(q, values, (err, results) => {
        if (err) {
            callback(err);
        } else if (results.affectedRows !== 1) {
            callback(new Error("更新失败，请稍后再试！"));
        } else {
            callback(null, "更新成功！", 0);
        }
    });
};


// //输入订单号的部分和用户ID
// exports.orderIdSearch = (req, res) => {
//    const order_id = req.query.order_id;
//     const user_id = req.query.user_id;
//     const values = [`%${order_id}%`, user_id, user_id];

//     const q = `SELECT * FROM orders WHERE order_id LIKE ? and (buyer_id = ? or seller_id = ?)`;

//     db.query(q, values, (err, results) => {
//         if (err) return res.status(500).send(err);
//         res.send({
//             status: 0,
//             message: '搜索完成！',
//             data: results,
//         });
//     });
// };

// //输入商品名和用户id
// exports.orderGoodsNameSearch = (req, res) => {
//     const goods_name = req.query.goods_name;
//     const user_id = req.query.user_id;
//     const value= [`%${goods_name}%`, user_id, user_id];
//     const q = `
//       SELECT * 
//       FROM orders 
//       JOIN goods ON order.goods_id = goods.goods_id
//       WHERE goods.goods_name LIKE ? and (buyer_id = ? or seller_id = ?)
//     `;

//     db.query(q, value, (err, results) => {
//         if (err) return res.status(500).send(err);
//         res.send({
//             status: 0,
//             message: '搜索完成！',
//             data: results,
//         })
//     });
// }